package com.gitee.empty_null.starter.configuration;

import com.gitee.empty_null.authorization.customizer.OAuth2AuthorizeHttpRequestsCustomizer;
import com.gitee.empty_null.authorization.customizer.OAuth2ResourceServerConfigurerCustomizer;
import com.gitee.empty_null.authorization.handler.OAuth2AuthenticationFailureHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @author xuhainan
 * @date 2024/1/16 14:29
 * @region hefei
 */
@Configuration
@EnableWebSecurity
public class DefaultSecurityConfiguration {

    @Bean
    SecurityFilterChain defaultSecurityFilterChain(
            HttpSecurity httpSecurity,
            OAuth2ResourceServerConfigurerCustomizer oAuth2ResourceServerConfigurerCustomizer,
            OAuth2AuthorizeHttpRequestsCustomizer oAuth2AuthorizeHttpRequestsCustomizer
    ) throws Exception {
        // 禁用CSRF 开启跨域
        httpSecurity.csrf(AbstractHttpConfigurer::disable)
                .cors(AbstractHttpConfigurer::disable);

        // @formatter:off
        httpSecurity
                .authorizeHttpRequests(oAuth2AuthorizeHttpRequestsCustomizer)
                .formLogin(Customizer.withDefaults())
                .oauth2ResourceServer(oAuth2ResourceServerConfigurerCustomizer)
                .exceptionHandling(exceptions->{
                    OAuth2AuthenticationFailureHandler failureHandler = new OAuth2AuthenticationFailureHandler();
                    exceptions.authenticationEntryPoint(failureHandler);
                    exceptions.accessDeniedHandler(failureHandler);
                })
        ;
        // @formatter:on
        return httpSecurity.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    public OAuth2AuthorizeHttpRequestsCustomizer oAuth2AuthorizeHttpRequestsCustomizer() {
        return new OAuth2AuthorizeHttpRequestsCustomizer();
    }


}
